<script setup>
import { ref } from 'vue'
// 导入组件
import channelSelect from './ChannelSelect.vue'

import { ElMessage } from 'element-plus'

// 导入 icon ‘+‘ 符号
import { Plus } from '@element-plus/icons-vue'

// 导入 发布文章的api
import { AddArtMangeService } from '@/api/articel.js'

// 导入api
import { GetMangerInfo, artEditService } from '@/api/articel.js'

// 导入图片转换成为文件的api
import { imageUrlToFile } from '@/utils/imageUrlToFile.js'

// 导入 富文本编辑器的组件
// import { QuillEditor } from '@vueup/vue-quill'
// import '@vueup/vue-quill/dist/vue-quill.snow.css'
const visibleDrawer = ref(false)

import { baseURL } from '@/utils/request.js'
// const baseURL = 'http://big-event-vue-api-t.itheima.net' // 数据库的基地址

const defaultData = {
  title: '',
  cate_id: '',
  content: '',
  cover_img: '',
  state: ''
}
const formModel = ref({ ...defaultData })
function removeHTMLTags(str) {
  return str.replace(/<[^>]*>/g, '')
}
// 控制弹出的方法 open()
const open = async (row) => {
  visibleDrawer.value = true
  if (row.id) {
    console.log('编辑回显')
    const res = await GetMangerInfo(row.id)
    formModel.value = res.data.data
    formModel.value.content = removeHTMLTags(formModel.value.content)
    imgUrl.value = baseURL + formModel.value.cover_img
    // 提交给后台，需要的是 file 格式的，将网络图片，转成 file 格式
    // 网络图片转成 file 对象, 需要转换一下
    formModel.value.cover_img = await imageUrlToFile(
      imgUrl.value,
      formModel.value.cover_img
    )
  } else {
    console.log('添加功能')
    formModel.value = { ...defaultData }
    imgUrl.value = ''
    formModel.value.content = ''
  }
}

// 文件上传的处理
const imgUrl = ref('')
const onUploadFile = (uploadFile) => {
  imgUrl.value = URL.createObjectURL(uploadFile.raw) // 渲染上传的图片到页面
  formModel.value.cover_img = uploadFile.raw // 把图片文件对象 给要传到后台的数据对象 formModel
}

// 发布和草稿按钮
const emit = defineEmits(['success'])
const onPublish = async (state) => {
  // 将已发布还是草稿状态，存入 state
  formModel.value.state = state

  // 转换 formData 数据
  const fd = new FormData()
  for (let key in formModel.value) {
    fd.append(key, formModel.value[key])
  }

  console.log(fd)
  //编辑请求
  if (formModel.value.id) {
    await artEditService(fd)
    ElMessage.success('编辑成功')
    visibleDrawer.value = false // 控制抽屉弹层
    emit('success', 'edit')
  } else {
    // 添加请求
    await AddArtMangeService(fd)
    ElMessage.success('添加成功')
    visibleDrawer.value = false
    emit('success', 'add')
  }
  visibleDrawer.value = false
}

// 暴露自己的 open 方法 这样父亲可以用
defineExpose({
  open
})
</script>
<template>
  <el-drawer
    v-model="visibleDrawer"
    direction="rtl"
    :title="formModel.id ? '编辑文章' : '添加文章'"
    size="50%"
  >
    <!-- 发表文章表单 -->
    <el-form :model="formModel" ref="formRef" label-width="100px">
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="formModel.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="文章分类" prop="cate_id">
        <!-- 下拉菜单 -->
        <channelSelect
          v-model="formModel.cate_id"
          :style="{ width }"
        ></channelSelect>
        <!-- ----------------- -->
      </el-form-item>
      <el-form-item label="文章封面" prop="cover_img">
        <!-- 文件上传 -->
        <!-- 当文件发生改变的时候出发 onUploadFile 事件方法 -->
        <el-upload
          class="avatar-uploader"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="onUploadFile"
        >
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容" prop="content">
        <div class="editor">
          <textarea
            name=""
            id=""
            cols="30"
            rows="10"
            v-model="formModel.content"
          ></textarea>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onPublish('已发布')">发布</el-button>
        <el-button type="info" @click="onPublish('草稿')">草稿</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style scoped lang="scss">
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
